package com.powernode.ajax.controller;

import com.powernode.ajax.mapper.UserMapper;
import com.powernode.ajax.pojo.User;
import com.powernode.ajax.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class Request1Controller {
    @RequestMapping(value = "/postrequest",method = RequestMethod.POST)
    public void ajax01(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        out.print("<h1>Hello World!</h1>");

    }

    @RequestMapping(value = "/formrequest",method = RequestMethod.POST)
    public void ajaxform(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取提交数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        PrintWriter out = response.getWriter();
        out.print("用户名："+username+",密码："+password);
    }

    @RequestMapping(value = "ajaxrequest02",method = RequestMethod.POST)
    public void ajax02(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("spring.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();    sqlSession.commit();  sqlSession.close(); // insert delete update需要提交
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        UserService userService = applicationContext.getBean("userService", UserService.class);
        String username = request.getParameter("username");
        User user = userService.select(username);
        Boolean flag = false;
        if(user != null){
            //查到了，说明这个用户名已经存在了
            flag = true;
        }else{
            //这个用户名不存在，可以使用
        }
        //响应结果到浏览器
        PrintWriter out = response.getWriter();
        if(flag){
            //用户已存在，不可以
            out.print("<font color='red'>对不起，用户已存在</font>");
        }else{
            //用户不存在
            out.print("<font color='green'>用户名可以使用</font>");

        }


    }
}
